﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;

public class BaseRptPage : Page
{
    public DbHelper db = new DbHelper();
    public MyDbHelper mydb = new MyDbHelper();
    BaseDataPage bp = new BaseDataPage();
    protected string mid = "";
    public BaseRptPage() { }
    protected virtual void Page_Load(object sender, EventArgs e)
    {
        mid = Request.Params["mid"];
        if (string.IsNullOrEmpty(mid))
        {
            Response.Write("<script type='text/javascript'>alert('地址错误，无法访问！');window.location.href = 'welcome.html';</script>");
            return;
        }

        if (!IsPostBack)
        {
            CheckModulesRights(mid, "M_Browse", "您没有权限操作此模块，请联系管理员！", "welcome.html");
            bp.InsertActionLog(Session["UserID"].ToString(), mid, "浏览", DateTime.Now.ToString());
        }

    }

    protected bool CheckModulesRights(string mid,string action,string msg,string url)
    {
        string isBrowse = mydb.DM_GetExecuteScalarObj("select "+action+" from sys_modulerights where mid=" + mid
            + " and userid=" + Session["UserID"]).ToString();
        if (string.IsNullOrEmpty(isBrowse))
        {
            Response.Write("<script type='text/javascript'>alert('"+msg+"');window.location.href = '"+url+"';</script>");
            return false;
        } if (isBrowse.ToLower() == "-1")
        {
            Response.Write("<script type='text/javascript'>alert('" + msg + "');window.location.href = '"+url+"';</script>");
            return false;
        }
        if (isBrowse.ToLower() == "false")
        {
            Response.Write("<script type='text/javascript'>alert('"+msg+"');window.location.href = '"+url+"';</script>");
            return false;
        }
        return true;
    }

    protected virtual string GetSortedFields()
    {
        string sortedField = "";
        //获取排序字段的信息
        if (ViewState["SortedField"] != null)
        {
            //如果存在排序信息，则将排序信息转换为字典存储
            Dictionary<string, string> sorted = (Dictionary<string, string>)ViewState["SortedField"];
            //便利取值
            foreach (KeyValuePair<string, string> kvp in sorted)
            {
                //key排序字段，value排序信息
                sortedField = kvp.Key + " " + kvp.Value;
            }
        }
        return sortedField;
    }

    // <summary>
    /// 将网格数据导出到Excel
    /// </summary>
    /// <param name="ctrl">网格名称(如GridView1)</param>
    /// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>
    /// <param name="FileName">要保存的文件名</param>
    public void GridViewToExcel(Control ctrl, string FileType, string FileName)
    {
        if (!CheckModulesRights(mid, "M_Export", "您没有权限操作此功能，请联系管理员！",""))
        {
            return;
        }
        bp.InsertActionLog(Session["UserID"].ToString(), mid, "导出", DateTime.Now.ToString());
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
        HttpContext.Current.Response.AppendHeader("Content-Disposition",
            "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
        HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 
        ctrl.Page.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctrl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
        
    }
    /// <summary>
    /// ReLoad this VerifyRenderingInServerForm is neccessary
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
    }

    protected virtual void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //判断是否进行排序
            if (ViewState["SortedField"] != null)
            {
                //恢复排序信息
                Dictionary<string, string> order = (Dictionary<string, string>)ViewState["SortedField"];
                //循环表头的单元格，判断是否有需要排序的单元格
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.Cells[i].Controls.Count > 0)
                    {
                        //是否是排序字段信息
                        LinkButton lb = e.Row.Cells[i].Controls[0] as LinkButton;
                        if (lb != null)
                        {
                            //反序和降序
                            if (order.ContainsKey(lb.CommandArgument))
                            {
                                Literal li = new Literal();
                                if (order[lb.CommandArgument] == "ASC")
                                {
                                    li.Text = "▲";
                                }
                                else
                                {
                                    li.Text = "▼";
                                }
                                //
                                e.Row.Cells[i].Controls.Add(li);
                            }
                        }
                    }
                }
            }
        }
    }
    protected  virtual void GridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        //
        Dictionary<string, string> sorted = new Dictionary<string, string>();
        //从ViewState读取上一次的排序信息。
        if (ViewState["SortedField"] == null)
        {
            //如果没有排序信息，则将当前点击的对象（即点击的排序字段）和排序信息添加到字典中
            sorted.Add(e.SortExpression, "ASC");
            //将排序信息放在字典中保存
            ViewState["SortedField"] = sorted;
        }
        else
        {
            //判断是否点击相同的排序，如果是相同的排序，
            //就是用反序
            //如果不是想通的排序，那就新的派讯，是用升序
            sorted = (Dictionary<string, string>)ViewState["SortedField"];
            if (sorted.ContainsKey(e.SortExpression))
            {
                if (sorted[e.SortExpression] == "ASC")
                {
                    sorted[e.SortExpression] = "DESC";
                }
                else
                {
                    sorted[e.SortExpression] = "ASC";
                }
            }
            else
            {
                sorted.Clear();
                sorted.Add(e.SortExpression, "ASC");
                ViewState["SortedField"] = sorted;
            }
        }

        //重新加载数据
        GvBind();

    }

    public void GridviewColumsVisible(GridView grid)
    {
        string sql = @"select mu_id,lindx,fieldname,fielddisplay,mu_visible,fieldwidth from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid = " +mid+" and m.modulecode='"+grid.ID+"'"
                  + " and userid=" + Session["UserID"];

        DataSet ds = mydb.DM_GetDateSet(sql);
        int i=0;
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach(DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["mu_visible"].ToString().ToLower() == "true")
                {
                    grid.Columns[i].Visible = true;
                }
                else
                {
                    grid.Columns[i].Visible = false;
                }
                i++;
            }
        }
    }
    protected virtual void GvBind()
    {
        
    }
}
